package com.ruoyi.framework.shiro.service;

import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;

public class httpbaiduapi {
    /**
     * 使用POST格式发送form-data格式参数，并获取响应字符串
     *
     * @param path
     * @param params
     * @return
     */
    public static String sendSmsFormByPost(String path, Map<String, Object> params) {
        URL u = null;
        HttpURLConnection con = null;
        // 构建请求参数
        StringBuffer sb = new StringBuffer();
        if (params != null) {
            for (Map.Entry<String, Object> e : params.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            //去掉最后一个&
            sb.substring(0, sb.length() - 1);
        }
        // 尝试发送请求
        try {
            u = new URL(path);
            con = (HttpURLConnection) u.openConnection();
            //POST 只能为大写，严格限制，post会不识别
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            osw.write(sb.toString());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            //一定要有返回值，否则无法把请求发送给server端。
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
     * get提交
     *
     * @param httpUrl
     * @return
     */
    public static String doGet(String httpUrl) {
        //链接
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer result = new StringBuffer();
        try {
            //创建连接
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接超时时间
            connection.setReadTimeout(15000);
            //开始连接
            connection.connect();
            //获取响应数据
            if (connection.getResponseCode() == 200) {
                //获取返回的数据
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭远程连接
            connection.disconnect();
        }
        return result.toString();
    }

    private static final String HOSTARR = "http://restapi.amap.com/v3/geocode/regeo";
    private static final String HOST = "https://restapi.amap.com/v3/distance";
    // private static final String HOST = "http://122.114.79.163:7770/v3/distance";
    private static final String KEY = "761e73b6188fb868feee5b558dcbcd7a";

    /**
     * 参数:（出发点数组、目的点） 格式：经度,纬度
     * 返回: {
     * "status": "1",
     * "info": "OK",
     * "infocode": "10000",
     * "results": [{ //结果数组
     * "origin_id": "1", //第一个起点
     * "dest_id": "1", //目的地
     * "distance": "261278", //距离（米）
     * "duration": "14280" //预计时间（秒）
     * }]
     * }
     */
    public static String mapDistanceMethod(String[] origins, String destination) {
        String responseEntity = null;
        for (int i = 0; i < 5 && responseEntity == null; i++) {
            responseEntity = mapDistance(origins, destination);
        }
        return responseEntity;
    }

    /**
     * 通过经纬度转换实际地址 经，纬度
     *
     * @param location
     * @return
     */
    public static String getLocationAddr(String location) {
        List<NameValuePair> list = new LinkedList<>();
        list.add(new BasicNameValuePair("key", KEY));
        list.add(new BasicNameValuePair("output", "JSON"));
        list.add(new BasicNameValuePair("location", location));
        String responseEntity = null;
        String addr = "";
        try {
            HttpGet httpGet = new HttpGet(new URIBuilder(HOSTARR).setParameters(list).build());
            httpGet.setConfig(RequestConfig.custom().setConnectTimeout(2000).build());
            HttpResponse response = HttpClients.createDefault().execute(httpGet);
            responseEntity = EntityUtils.toString(response.getEntity(), "UTF-8");
            JSONObject jsonObject = JSON.parseObject(responseEntity);
            // System.out.println("-------响应结果-------\n" + jsonObject.toJSONString());
            addr = jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent")
                    .getJSONObject("building").getString("name");

            if (addr.equals("[]")) {
                addr = jsonObject.getJSONObject("regeocode").getString("formatted_address");
                addr = addr + jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent")
                        .getJSONObject("streetNumber").getString("number");
                //切除省市
    /* if(addr.indexOf("省")>0){
    addr=addr.substring(addr.indexOf("省")+1,addr.length());
    }
    if(addr.indexOf("市")>0){
    addr=addr.substring(addr.indexOf("市")+1,addr.length());
    }*/
            }

        } catch (Exception e) {
            if (e instanceof ConnectTimeoutException) {
                //   System.out.println("-------请求超时-------");
            } else {
                e.printStackTrace();
            }
        }
        return addr;
    }

    private static String mapDistance(String[] origins, String destination) {
        StringBuilder originBuilder = new StringBuilder();
        for (int i = 0; i < origins.length; i++) {
            originBuilder.append(origins[i]);
            if (i < origins.length - 1) {
                originBuilder.append("|");
            }
        }
        List<NameValuePair> list = new LinkedList<>();
        list.add(new BasicNameValuePair("key", KEY));
        list.add(new BasicNameValuePair("output", "JSON"));
        list.add(new BasicNameValuePair("origins", originBuilder.toString()));
        list.add(new BasicNameValuePair("destination", destination));
        String responseEntity = null;
        try {
            HttpGet httpGet = new HttpGet(new URIBuilder(HOST).setParameters(list).build());
            httpGet.setConfig(RequestConfig.custom().setConnectTimeout(2000).build());
            HttpResponse response = HttpClients.createDefault().execute(httpGet);
            responseEntity = EntityUtils.toString(response.getEntity(), "UTF-8");
            //System.out.println("-------距离测量响应结果-------\n" + responseEntity);
        } catch (Exception e) {
            if (e instanceof ConnectTimeoutException) {
                //  System.out.println("-------请求超时-------");
            } else {
                e.printStackTrace();
            }
        }
        return responseEntity;
    }

    public static void main(String[] args) throws InterruptedException {
        //getLocationAddr("113.242439,35.1863620");
        System.out.println(getLocationAddr("120.126032,29.328647"));
        // String[] origins = new String[]{"116.481028,39.989643", "114.481028,39.989643", "115.481028,39.989643"};
        // String destination = "114.465302,40.004717";
        // for (int i = 0; i < 100; i++) {
        // MapDistanceUtil.mapDistanceMethod(origins, destination);
        // System.out.println("---------第" + i + "次请求");
        // Thread.sleep(200);
        // }
    }
}
